<?php
  /* TODO : REFERER CHECK */
define("G_GEO_SUCCESS"		  ,'200');
define("G_GEO_SERVER_ERROR"	  ,'500');
define("G_GEO_MISSING_QUERY"	  ,'601');
define("G_GEO_UNKNOWN_ADDRESS"	  ,'602');
define("G_GEO_UNAVAILABLE_ADDRESS",'603');
define("G_GEO_BAD_KEY"		  ,'610');
define("G_GEO_TOO_MANY_QUERIES"   ,'620');

function geo_code($qry) {
  $result = file_get_contents("http://maps.google.com/maps/geo?gl=KR&q=" . $qry
			      . "&output=csv&sensor=true_or_false&key=ABQIAAAAU94cGc0Q2UxRLa2lbmWZExT5JgxXvSaZKHPhbuBT5qruoAfgahRigr5cgUhGY0zuTzMaU9Ef--js5g");

  $slice = explode(',' ,$result);
  $status_code = $slice[0];

  $lat = $slice[2];
  $lng = $slice[3];

  if ($status_code == G_GEO_SUCCESS)
    return array($lat, $lng);
  else
    return false;
}

if (isset($argv[1])) {
  $length = sizeof($argv);
  $query = '';
  for ($i=1; $i < $length; ++$i) {
    $query .= $argv[$i] . ' ';
  }
  $query = trim($query);
  $qry = rawurlencode($query);
  $result = geo_code($qry);
  if ($result == false) {
    echo "ERROR";
    exit;
  }
  echo $result[0] . "\n";
  echo $result[1] . "\n";
 }
 else if (isset($_GET['q'])) {
   $qry = rawurlencode($_GET['q']);
   $result = geo_code($qry);
   if ($result == false) {
     echo '{"error":500}';
   } else {
     echo '{"lat":"' . $result[0] . '", "lng":"' . $result[1] . '"}';
   }
 } else {}
?>
